import time

from uiautomator2 import Device

from le_engine.base import LittleEmpire
from le_engine.config import CommonConfig, IconName
from utils.logger import log
from utils.utils import CommonUtils


class CageUtils:
    Captured = "Captured"
    Digging = "Digging"
    Error = "Error"
    Empty = "Empty"
    Restart = "Restart"

    def __init__(self, le: LittleEmpire, event=None):
        self.le = le
        self.client: Device = self.le.get_client()

        self.event = event

    @property
    def cage_position(self):
        config = CommonConfig.cage_config.get(self.le.username, CommonConfig.cage_config["common"])
        if config:
            return config['cage_position']
        else:
            return self.le.error_exit("缺少牢笼配置")

    @property
    def cage_swap_list(self):
        config = CommonConfig.cage_config.get(self.le.username, CommonConfig.cage_config["common"])
        if config:
            return config['cage_swap_list']
        else:
            return self.le.error_exit("缺少牢笼配置")

    def focus_cage(self):
        # 滑动屏幕，找到牢笼
        for item in self.cage_swap_list:
            self.client.swipe(*item, duration=0.5)

    def enter_cage(self, index=0):
        log.info(f"寻找 {index + 1} 号牢笼", extra={"pk": self.le.pk})
        self.client.click(*self.cage_position[index])

        if self.le.im.find_image(CommonConfig.img_path(IconName.paiqian)):
            return False, self.Captured

        if self.le.im.find_image(CommonConfig.img_path(IconName.chejun)):
            return False, self.Digging

        self.client.click(*CommonConfig.cage_check)
        return self.is_enter_cage(index)

    def next_page(self):
        self.client(text="换一批").click_exists()

    def attack(self):
        if self.client(text="请您制定进攻计划").wait(timeout=CommonConfig.n_t_o):
            if self.le.im.click_image(CommonConfig.img_path(IconName.ll_attack)):
                time.sleep(1)
                return True
        return False


    def is_enter_cage(self, index=None) -> (bool, str):
        if self.client(text="你想抓谁做奴隶").wait(timeout=CommonConfig.n_t_o):
            log.info("成功进入牢笼", extra={"pk": self.le.pk})
            return True, self.Empty
        elif self.client(text="信件").wait(timeout=CommonConfig.n_t_o):
            log.info("进入牢笼失败", extra={"pk": self.le.pk})
            return False, self.Error
        return False, ""

    def wait_attack(self):
        # 如果所有牢笼都在进攻，识别行军最大时间，进行等待
        self.client.click(*CommonConfig.email_position)
        time.sleep(1)
        self.client.click(*CommonConfig.attack_report_position)

        self.client(textContains="你的部队").wait(timeout=CommonConfig.n_t_o)

        time_info = [i.get_text() for i in self.client(textContains="你的部队")]
        if time_info:
            max_seconds = max([CommonUtils.extract_seconds(item) for item in time_info])
            log.info(f"所有牢笼都在进攻，需要等待:{max_seconds}秒", extra={"pk": self.le.pk})
            for remaining in range(max_seconds, 0, -1):
                if self.event and self.event.is_set():
                    log.info("已停止刷功勋", extra={"pk": self.le.pk})
                    return False, None
                minutes = remaining // 60
                seconds = remaining % 60
                print(f"\r还剩 {minutes} 分 {seconds} 秒", end="", flush=True)
                time.sleep(1)
            log.info("等待结束", extra={"pk": self.le.pk})
            self.client.click(*CommonConfig.close_position)
            time.sleep(5)
        return True, None